import { Component, OnInit, Input, Output, EventEmitter, HostListener, SimpleChanges, QueryList, ViewChild, ViewChildren, ElementRef } from '@angular/core';
import * as pdfjsLib from "pdfjs-dist";
import { fromEvent } from 'rxjs';

@Component({
  selector: 'app-diypdf',
  templateUrl: './diypdf.component.html',
  styleUrls: ['./diypdf.component.css']
})
export class DiypdfComponent implements OnInit {

  canDraw: boolean = false; // pdf是否可以绘制
  pdfDoc: any = null;
  pages: number = 0;
  pagesList: any[] = [1, 2, 3];
  currentPage: 0;
  pageHeight: 0;
  pageWidth: 0;
  renderList: any[] = []; // 渲染的页码数组
  timerIndex: any;
  url: Object = null;
  pageNo: number = 1;
  rectObj: any[] = []; // 绘制矩阵的对象  page: [location, location,...]
  ele2Hightlight: any; // 要编辑的元素对象 由 ElementDisplay 组件点击编辑事件传递过来,
  editHightlight: any[] = [];
  pointArray: any[] = [];// 每次绘制的时候pointArray的集合
  selectionObj: any = {}; // 绘制聚焦的框, page: page, location: [] 
  private pdfData: string[];
  private pageContainer: any[];
  public manualRender: boolean = false;
  private that: any;
  $pageClick: any;
  highlight: any[] = [];
  scale: number = 1;
  pdfSize: any[] = []

  //接受
  @Input() set pdf_Size(value: []) {
    this.pdfSize = value;
  };//接收父组件的值
  @Input() renderPages: number = 5;
  @Input() set pdf_Data(value: []) {
    this.pdfData = value;
    if (value.length > 0) {
      console.log(this.pdfSize);
      this.getUrl()
      this.getRectObj()
    }
  }//接收父组件的值
  @Input() set openDraw(value: boolean) {
    this.canDraw = value;
  }
  @Input() set highBlock(value: []) {
    this.highlight = value;
    this.getRectObj();
    // if (isAgainDraw) {
    //   console.log("需要删除");
    //   this.delDraw(this.pageNo);
    // }
  }
  @Input() set delBlock(value: []) {
    if (value.length > 0)
      this.delDraw(this.pageNo);
  }

  @Input() set changePage(value: number) {
    if (value != 0) {
      this.scrollToPage(value);
    }
  }


  //判断是否减少
  lengthSubChange(val1, val2) {
    let length1 = 0;
    val1.forEach(element => {
      if (element)
        length1 += element.length;
    });
    console.log(length1)
    let length2 = 0;
    val2.forEach(element => {
      console.log(element)
      if (element)
        length2 += element.length;
    });
    console.log(length2)
    return length2 < length1;
  }

  //获取dom节点
  // @ViewChild('pageContainer', { static: false }) pageContainer: any;
  @ViewChildren("pageContainer") pageContainerList: QueryList<any>;
  @ViewChild('pdfDetailContainer') pdfDetailContainer: ElementRef;

  //回传
  @Output() deletElementPoint = new EventEmitter<any>();
  @Output() deleteDrawRectList = new EventEmitter<any>();
  @Output() updateHL = new EventEmitter<any>();
  @Output() updatePage = new EventEmitter<any>();

  constructor() {
    pdfjsLib.GlobalWorkerOptions.workerSrc = './assets/build/pdf.worker.js';
  }

  ngOnInit(): void {
    this.that = this;
    // console.log(this);
    this.$pageClick = fromEvent(window, 'scroll').subscribe(() => {
      // console.log(this);
    });
    // console.log(pdfjsLib.GlobalWorkerOptions.)
    if (!this.manualRender) {
      // document.addEventListener('scroll', this.documentScroll, true)

    }
  }

  ngOnDestroy() {

  }
  documentScroll() {
    // console.log(this);
    this.renderCurrent()
    // console.log("documentScroll");
  }

  checkRender(): void {
    this.timerIndex && clearTimeout(this.timerIndex);
    this.timerIndex = setTimeout(this.renderCurrent, 100)
  }

  test($event) {
    this.renderCurrent()
  }

  renderCurrent() {
    // this.$nextTick(() => {
    if (this.pages <= 0) return
    if (!this.pageHeight) return
    this.pageContainer = this.pageContainerList.toArray();
    if (!this.pageContainer[0]) return
    // console.log(this.pageContainer[0]getBoundingClientRect());
    let dpfBoxTop = this.pdfDetailContainer.nativeElement.getBoundingClientRect().top + 5;
    const rect = this.pageContainer[0].nativeElement.getBoundingClientRect()
    console.log('rect', rect)
    if (rect.top >= 0) {
      this.scrollToPage(1)
    } else {
      console.log("-rect.top", -rect.top, this.pageHeight);
      let page = Math.floor(-(rect.top - dpfBoxTop) / this.pageHeight) + 1
      console.log('rect', page)
      if (page > this.pages) page = this.pages
      // this.scrollToPage(page)
      this.updatePage.emit({ "curr": page, "all": this.pages });
    }
    // })
  }

  // ngOnChanges(changes: SimpleChanges): void {
  //   console.log(JSON.stringify(changes, null, 2));
  // }
  ngAfterViewInit() {
    this.pageContainer = this.pageContainerList.toArray();
    // console.log(this.pageContainer)
  }

  getUrl() {
    // const pdfData = atob(this.pdfData[0])
    const pdfData = atob(this.pdfData[0].substring(this.pdfData[0].indexOf(',') + 1))
    // console.log(pdfData);
    //const CMAP_URL = 'https://unpkg.com/pdfjs-dist@2.0.489/cmaps/';
    const CMAP_URL = './assets/cmaps/';
    this.url = {
      data: pdfData,
      cMapUrl: CMAP_URL,
      cMapPacked: true,
    }
    this.getPDFFile()
  }

  getPDFFile() {
    if (!this.url) return
    // console.log(this.url);
    const loadingTask = pdfjsLib.getDocument(this.url)
    loadingTask.promise.then(pdf => {
      this.pdfDoc = pdf
      this.pages = this.pdfDoc.numPages;
      this.pagesList = this.range(this.pdfDoc.numPages);
      // this.$nextTick(() => {
      //   this.pages && this.scrollToPage(1)
      // })
      this.scrollToPage(1)
    })
  }

  // 将对象数字转换为数组
  //range自定义的函数名称 （num：number）利用 ts 的特性 定义只接受number类型的值 
  range(num: number) {
    var arr = [];
    for (var i = 1; i <= num; i++) {
      arr.push(i);
    }
    // console.log(arr);
    return arr;
  }

  scrollToPage(pageNo) { // 滚动到当前位置
    console.log('scroll to pageNo: ', pageNo, this.currentPage, this.renderPages)
    this.pageContainer = this.pageContainerList.toArray();
    // console.log(this.pageContainer);
    // console.log(this.pdfDetailContainer);

    if (this.currentPage === pageNo) return
    this.currentPage = pageNo
    let oldList = [...this.renderList]
    // console.log('oldList', oldList)
    const list = []

    for (let page = pageNo - this.renderPages; page <= pageNo + this.renderPages; page++) {
      list.push(page)
    }
    // console.log('list', list)
    for (let idx = list.length; idx >= 0; idx--) {
      if (list[idx] > this.pages || list[idx] < 1) list.splice(idx, 1)
    }
    // console.log('newList', list)
    // const set1 = new Set(oldList);
    // const set2 = new Set(list);
    // const intersection = this.set_intersection(set1, set2)
    // 这是移除数组
    const intersection = this.subtraction(oldList, list)
    // 这是新添加的数组
    const intersection1 = this.subtraction(list, oldList)
    // console.log('intersection', intersection)
    // console.log('intersection1', intersection1)
    //新注释-开始
    // this.$nextTick(() => {
    this.renderList = list
    intersection.forEach(page => {
      let that = this;
      setTimeout(function () { that.clearPage(page) }, 1000)

    })
    intersection1.forEach(page => {
      let that = this;
      setTimeout(function () { that.renderPage(page) }, 1000)

    })

    // console.log(this.pageHeight)
    this.pdfDetailContainer.nativeElement.scrollTop = this.pageHeight * (pageNo - 1);

    this.updatePage.emit({ "curr": pageNo, "all": this.pages });

    // this.renderList.forEach(page => {
    //   this.renderPage(page)
    // })
    // })
    //新注释-结束
  }

  /**
     * 取出数组的不重合的部分
     */
  /**
   * 清空所有的页面数据,算是释放内存吧
   */
  clearPage(pageNo) {
    const containerNode = null; //this.$refs.pageContainer[pageNo - 1]
    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('canvas')

    if (!canvas) return
    const ctx = canvas.getContext('2d')
    canvas.width = 0
    canvas.height = 0
  }
  renderPage(pageNo) {
    this.pdfDoc.getPage(pageNo).then(page => {
      this.pageContainer = this.pageContainerList.toArray();
      // console.log(this.pageContainer);
      const containerNode = this.pageContainer[pageNo - 1]
      if (!containerNode) return
      const canvas = containerNode.nativeElement.querySelector('canvas')
      if (!canvas || canvas.__rendered) return
      const ctx = canvas.getContext('2d')
      const dpr = window.devicePixelRatio || 1
      const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
      const ratio = dpr / bsr
      let viewport = page.getViewport({ scale: 1.5 })
      canvas.width = viewport.width * ratio
      canvas.height = viewport.height * ratio
      canvas.style.width = viewport.width + 'px'
      canvas.style.height = viewport.height + 'px'
      this.pageWidth = viewport.width
      this.pageHeight = viewport.height
      ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
      const renderCtx = {
        canvasContext: ctx,
        viewport
      }

      // console.log(this.pageHeight);
      page.render(renderCtx)
      canvas.__rendered = true
      this.drawRect(pageNo)
    })
  }

  drawRect(pageNo) { // 计算缩放比例子 绘制高亮
    // console.log(this.pdfSize)
    this.pageContainer = this.pageContainerList.toArray();
    const containerNode = this.pageContainer[pageNo - 1]
    if (!containerNode) return

    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    if (!canvas || canvas.__rendered) return

    const ctx = canvas.getContext('2d')
    const dpr = window.devicePixelRatio || 1
    const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio ||
      ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio ||
      ctx.backingStorePixelRatio || 1
    const ratio = dpr / bsr
    // console.log("ratio", ratio);
    canvas.width = this.pageWidth * ratio
    canvas.height = this.pageHeight * ratio
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    // console.log(this.pdfSize)
    ctx.clearRect(0, 0, this.pdfSize[0], this.pdfSize[1])
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
    const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
      this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]

    // const scale = this.scale;
    ctx.fillStyle = "rgba(94,124,224,0.30)"
    // 绘制当前页面的所有高亮元素
    this.rectObj && this.rectObj[pageNo] && this.rectObj[pageNo].map(rect => {
      ctx.fillRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
    })
    // console.log(this.editHightlight);
    // 绘制当前可编辑的高亮元素框
    if (this.editHightlight && this.editHightlight.length > 0) {
      this.editHightlight.map((item: any) => {
        if (item.locations && item.locations.length > 0) {
          // locations 是数组
          item.locations.map(itemLocation => {
            console.log(itemLocation);
            if (itemLocation.page === pageNo) {
              itemLocation.location && itemLocation.location.length > 0 && itemLocation.location.map(rect => {
                ctx.strokeStyle = 'green'
                ctx.strokeRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
              })
            }
          })
        }
      })
    }

    //
    if (this.selectionObj) {
      if (this.selectionObj.page == pageNo) {
        const rect = this.selectionObj.location
        ctx.strokeStyle = 'blue'
        ctx.strokeRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
      }
    }

    ctx.save()
  }
  drawHL(pageNo, rect) { // 修改要素高亮区域时 绘制函数 未完成 调用在 canvasUp
    this.pageContainer = this.pageContainerList.toArray();
    const containerNode = this.pageContainer[pageNo - 1]
    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    if (!canvas || canvas.__rendered) return

    const ctx = canvas.getContext('2d')
    const dpr = window.devicePixelRatio || 1
    const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio ||
      ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio ||
      ctx.backingStorePixelRatio || 1
    const ratio = dpr / bsr
    canvas.width = this.pageWidth * ratio
    canvas.height = this.pageHeight * ratio
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
    const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
      this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]
    // const scale = this.scale;
    ctx.fillStyle = "rgba(94,124,224,0.50)"

    ctx.fillRect(rect.startPoint[0] * scale, rect.startPoint[1] * scale, rect.width * scale, rect.height * scale);
    ctx.save()
  }
  /************************************* 框选 ****************************************/
  canvasDown(e, page) { // 画布按下
    // console.log("canvasDown" + this.canDraw);
    if (!this.canDraw) return
    this.pageContainer = this.pageContainerList.toArray();
    const containerNode = this.pageContainer[page - 1]

    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    if (!canvas) return
    console.log('###e', e)
    canvas._startEvent = e
  }
  canvasMove(e, page) { // 鼠标移动
    // console.log(this.rectObj)
    // console.log(page)
    if (!this.canDraw) return
    this.pageContainer = this.pageContainerList.toArray();
    const containerNode = this.pageContainer[page - 1]
    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    if (!canvas) return
    if (canvas._startEvent) {
      const ctx = canvas.getContext('2d')
      const dpr = window.devicePixelRatio || 1
      const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
      const ratio = dpr / bsr
      canvas.width = this.pageWidth * ratio
      canvas.height = this.pageHeight * ratio
      ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
        this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]
      // const scale = this.scale;
      canvas._rect = { x: canvas._startEvent.layerX, y: canvas._startEvent.layerY, width: e.layerX - canvas._startEvent.layerX, height: e.layerY - canvas._startEvent.layerY }
      ctx.strokeStyle = 'white'
      ctx.fillStyle = "rgba(94,124,224,0.50)"
      this.dealDrawRect(canvas._rect)
      // console.log('canvas._rect', canvas._rect)
      ctx.strokeRect(canvas._rect.x, canvas._rect.y, canvas._rect.width, canvas._rect.height)
      ctx.fillRect(canvas._rect.x, canvas._rect.y, canvas._rect.width, canvas._rect.height)
      this.pointArray && this.pointArray.length > 0 && this.pointArray.map((item: any) => {
        ctx.strokeRect(item.x, item.y, item.width, item.height)
        ctx.fillRect(item.x, item.y, item.width, item.height)
      })
      if (this.rectObj[page]) {
        ctx.fillStyle = "rgba(94,124,224,0.30)"
        this.rectObj[page].map(rect => {
          console.log(rect);
          ctx.fillRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
        })
      }
      // console.log('$$$$$$$$$$', this.editHightlight, page)
      if (this.editHightlight && this.editHightlight.length > 0) {
        this.editHightlight.map((item: any) => {
          // if(upItem && upItem.length> 0) {
          //   upItem.map(item => {
          if (item.locations && item.locations.length > 0) {
            // locations 是数组
            item.locations.map(itemLocation => {
              if (itemLocation.page == page) {
                itemLocation.location && itemLocation.location.length > 0 && itemLocation.location.map(rect => {
                  ctx.strokeStyle = 'green'
                  ctx.strokeRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
                })
              }
            })
          }
        })
      }
      ctx.save()
    }
  }
  canvasUp(e, page) { // 鼠标松开
    if (!this.canDraw) return
    // console.log('new HL in page:', page)
    this.pageContainer = this.pageContainerList.toArray();
    const containerNode = this.pageContainer[page - 1]
    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    if (!canvas) return
    if (canvas._startEvent) {
      canvas._startEvent = undefined
      if (canvas._rect && canvas._rect.width > 0 && canvas._rect.height > 0) {
        console.log('canvas._rect', canvas._rect)
        const x = canvas._rect.x
        const y = canvas._rect.y
        const width = canvas._rect.width
        const height = canvas._rect.height
        this.pointArray.push({ x, y, width, height }) // 这个是绘制后的矩阵的点数组信息
      }
      if (canvas._rect && canvas._rect.width !== 0 && canvas._rect.height !== 0) {
        const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
          this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]
        // const scale = this.scale;
        const startPoint = [canvas._rect.x, canvas._rect.y]
        console.log(startPoint)
        console.log(scale)
        const HL_height = canvas._rect.height
        const HL_width = canvas._rect.width
        const x1 = [Math.round(canvas._rect.x / scale), Math.round(canvas._rect.y / scale)]
        const x2 = [Math.round(canvas._rect.x / scale + canvas._rect.width / scale), Math.round(canvas._rect.y / scale)]
        const x3 = [Math.round(canvas._rect.x / scale), Math.round(canvas._rect.y / scale + canvas._rect.height / scale)]
        const x4 = [Math.round(canvas._rect.x / scale + canvas._rect.width / scale), Math.round(canvas._rect.y / scale + canvas._rect.height / scale)]
        const oneHLlocation = [x1, x2, x4, x3]
        console.log(oneHLlocation);
        const newHighlight = [{
          // label: this.ele2Hightlight.label,
          // text: this.ele2Hightlight.text,
          locations: [
            {
              page: page,
              location: [
                oneHLlocation
              ]
            }
          ]
        }]
        this.updateHL.emit(newHighlight);
        // this.$emit('updateHL', newHighlight)
        const rect = {
          startPoint: startPoint,
          height: HL_height,
          width: HL_width
        }
        canvas._rect = {}
        // this.drawHL(page, rect)
      }
    }
  }
  /**
 * 对自己绘制的矩阵进行判断，当前canvs._rect与之对比
 */
  dealDrawRect(rc1) {
    // console.log('this.pointArray', this.pointArray)
    this.pointArray && this.pointArray.length > 0 && this.pointArray.map((item, index) => {
      if (this.isOverlap(item, rc1)) {
        this.pointArray.splice(index, 1)
        this.deleteDrawRectList.emit(index);
        // this.$emit('deleteDrawRectList', index)
      }
    })
  }
  /**
   * 判断俩个矩阵对象是否重合
   */
  isOverlap(rc1, rc2) {
    if ((rc1.x + rc1.width) > rc2.x &&
      (rc2.x + rc2.width) > rc1.x &&
      (rc1.y + rc1.height) > rc2.y &&
      (rc2.y + rc2.height) > rc1.y)
      return true;
    else
      return false;
  }
  /**
     * 取出俩个数组的差集
     */
  subtraction(a, b) {
    const arr = a.filter((v) => {
      return b.indexOf(v) == -1
    })
    return arr
  }
  getRectObj() { // 处理highlight 数组，转成 hash 对象
    this.rectObj = []
    console.log(this.highlight);


    this.highlight.forEach(h1Item => {
      h1Item.forEach(h2Item => {
        if (h2Item.location && h2Item.location.length > 0) {
          console.log(this.rectObj[h2Item.page]);
          if (this.rectObj[h2Item.page]) {
            this.rectObj[h2Item.page] = [...this.rectObj[h2Item.page], h2Item.location]
            console.log(this.rectObj[h2Item.page])
          } else {
            this.rectObj[h2Item.page] = [h2Item.location]
          }

          console.log(this.rectObj);
          //
        }
      })
    });

    // this.highlight.map(items => {
    //   items.map(item => {
    //     if (item.locations && item.locations.length > 0) {
    //       // locations 是数组
    //       item.locations.map(itemLocation => {
    //         if (this.rectObj[itemLocation.page]) {
    //           if (itemLocation.location.length > 0) {
    //             this.rectObj[itemLocation.page] = [...this.rectObj[itemLocation.page], ...itemLocation.location]
    //           }
    //         } else {
    //           if (itemLocation.location.length > 0) {
    //             this.rectObj[itemLocation.page] = [...itemLocation.location]
    //           }
    //         }
    //       })
    //     }
    //   })
    // })
    // 处理rectObj数组
    for (const page in this.rectObj) {
      console.log(page)
      if (this.rectObj[page].length > 1) {
        this.rectObj[page].map((item, index) => {
          console.log(item);
          this.rectObj[page][index] = this.returnNewArr(item)
          this.rectObj[page].map((dItem, jndex) => {
            this.rectObj[page][jndex] = this.returnNewArr(dItem)
            if (index !== jndex) {
              if (this.isArArrOverlap(item, dItem)) {
                this.rectObj[page][index] = this.mergeTwoArr(item, dItem)
                this.rectObj[page].splice(jndex, 1)
              }
            }
          })
        })
      }
    }
    for (const page in this.rectObj) {
      if (this.rectObj[page].length > 1) {
        this.rectObj[page].map((item, index) => {
          this.rectObj[page][index] = this.returnNewArr(item)
          this.rectObj[page].map((dItem, jndex) => {
            this.rectObj[page][jndex] = this.returnNewArr(dItem)
            if (index !== jndex) {
              if (this.isArArrOverlap(item, dItem)) {
                this.rectObj[page][index] = this.mergeTwoArr(item, dItem)
                this.rectObj[page].splice(jndex, 1)
              }
            }
          })
        })
      }
    }
    for (const page in this.rectObj) {
      if (this.rectObj[page].length > 1) {
        this.rectObj[page].map((item, index) => {
          this.rectObj[page][index] = this.returnNewArr(item)
          this.rectObj[page].map((dItem, jndex) => {
            this.rectObj[page][jndex] = this.returnNewArr(dItem)
            if (index !== jndex) {
              if (this.isArArrOverlap(item, dItem)) {
                this.rectObj[page][index] = this.mergeTwoArr(item, dItem)
                this.rectObj[page].splice(jndex, 1)
              }
            }
          })
        })
      }
    }
    console.log('this.rectObj:', this.rectObj)
  }

  /**
     * 重新返回一个数组
     */
  returnNewArr(rec1) {
    console.log(rec1);
    let x0 = rec1[0][0]
    let x1 = rec1[1][0]
    let x2 = rec1[2][0]
    let x3 = rec1[3][0]
    let y0 = rec1[0][1]
    let y1 = rec1[1][1]
    let y2 = rec1[2][1]
    let y3 = rec1[3][1]
    const minX = Math.min(x1, x2, x3, x0)
    const maxX = Math.max(x1, x2, x3, x0)
    const minY = Math.min(y1, y2, y3, y0)
    const maxY = Math.max(y1, y2, y3, y0)
    // 左下角第四个点， x最小，y最大
    return [[minX, minY], [maxX, minY], [maxX, maxY], [minX, maxY]]
  }

  /**
    * 判断俩个数组矩阵是否重合
    */
  isArArrOverlap(rec1, rec2) {
    const x1 = rec1[0][0]
    const y1 = rec1[0][1]
    const w1 = rec1[1][0] - rec1[0][0]
    const h1 = rec1[3][1] - rec1[0][1]
    const x2 = rec2[0][0]
    const y2 = rec2[0][1]
    const w2 = rec2[1][0] - rec2[0][0]
    const h2 = rec2[3][1] - rec2[0][1]
    if (x1 + w1 >= x2 &&
      x2 + w2 >= x1 &&
      y1 + h1 >= y2 &&
      y2 + h2 >= y1)
      return true;
    else
      return false;
  }
  /**
     * 合并俩个重合的数组
     */
  mergeTwoArr(rec1, rec2) {
    let x0 = rec1[0][0]
    let x1 = rec1[1][0]
    let x2 = rec1[2][0]
    let x3 = rec1[3][0]
    let c0 = rec2[0][0]
    let c1 = rec2[1][0]
    let c2 = rec2[2][0]
    let c3 = rec2[3][0]
    let y0 = rec1[0][1]
    let y1 = rec1[1][1]
    let y2 = rec1[2][1]
    let y3 = rec1[3][1]
    let d0 = rec2[0][1]
    let d1 = rec2[1][1]
    let d2 = rec2[2][1]
    let d3 = rec2[3][1]
    // 左上角第一个点， x,y 最小的
    const minX = Math.min(x1, x2, x3, x0, c1, c2, c3, c0)
    const maxX = Math.max(x1, x2, x3, x0, c1, c2, c3, c0)
    const minY = Math.min(y1, y2, y3, y0, d1, d2, d3, d0)
    const maxY = Math.max(y1, y2, y3, y0, d1, d2, d3, d0)
    // 左下角第四个点， x最小，y最大
    return [[minX, minY], [maxX, minY], [maxX, maxY], [minX, maxY]]
  }

  // 双击删除框选内容 然后根据点的位置， 判断是新画的矩阵， 还是当前编辑的高亮的矩阵
  dbClick(e, page) {
    if (!this.canDraw) return
    const point = [e.layerX, e.layerY] // 当前的点位
    this.deletePointByDraw(point, page)
    this.deletePointByElement(point, page)
  }

  // 判断点是否在自己绘制的数组中。 this.pointArray
  deletePointByDraw(point, page) {
    let idx = -1
    this.pointArray.length > 0 && this.pointArray.map((item: any, index) => {
      if (item.x < point[0] < item.x + item.width && item.y < point[1] < item.y + item.height) {
        idx = index
      }
    })
    if (idx > -1) {
      this.pointArray.splice(idx, 1)
      this.againDraw(page)
    }
  }

  // 判断点是否在编辑的要素内， 如果在当前要素内，从displayList 数组里面删除该元素，重新绘制该页面
  deletePointByElement(point, page) {
    const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
      this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]
    // const scale = this.scale;
    const newPoint = [point[0] / scale, point[1] / scale]
    this.deletElementPoint.emit({ newPoint, page });
    // this.$emit('deletElementPoint', newPoint, page)
  }

  // 删除自己画的框以后重新绘制
  againDraw(page) {
    if (!this.canDraw) return
    this.pageContainer = this.pageContainerList.toArray();
    const containerNode = this.pageContainer[page - 1]
    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    if (!canvas) return
    const ctx = canvas.getContext('2d')
    const dpr = window.devicePixelRatio || 1
    const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
    const ratio = dpr / bsr
    canvas.width = this.pageWidth * ratio
    canvas.height = this.pageHeight * ratio
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0)

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.strokeStyle = 'red'
    ctx.fillStyle = "rgba(94,124,224,0.30)"
    // this.pointArray && this.pointArray.length > 0 && this.pointArray.map((item: any) => {
    //   ctx.strokeRect(item.x, item.y, item.width, item.height)
    //   ctx.fillRect(item.x, item.y, item.width, item.height)
    // })
    const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
      this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]
    if (this.rectObj[page]) {
      ctx.fillStyle = "rgba(94,124,224,0.30)"
      this.rectObj[page].length > 0 && this.rectObj[page].map(rect => {
        ctx.fillRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
      })
    }
    // 绘制当前可编辑的高亮元素框
    console.log('this.currentIndex', page, this.editHightlight)
    if (this.editHightlight && this.editHightlight.length > 0) {
      this.editHightlight.map((item: any) => {
        // if(upItem && upItem.length> 0) {
        //   upItem.map(item => {
        if (item.locations && item.locations.length > 0) {
          // locations 是数组
          item.locations.map(itemLocation => {
            if (itemLocation.page == page) {
              itemLocation.location && itemLocation.location.length > 0 && itemLocation.location.map(rect => {
                ctx.strokeStyle = 'green'
                ctx.strokeRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
              })
            }
          })
        }
      })
    }
    ctx.save()
  }

  // 前台删除操作
  delDraw(page) {
    this.pageContainer = this.pageContainerList.toArray();
    console.log(page);
    const containerNode = this.pageContainer[page - 1]
    console.log(containerNode);
    if (!containerNode) return
    const canvas = containerNode.nativeElement.querySelector('.drawBoard')
    console.log(canvas);
    if (!canvas) return
    const ctx = canvas.getContext('2d')
    const dpr = window.devicePixelRatio || 1
    const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
    const ratio = dpr / bsr
    canvas.width = this.pageWidth * ratio
    canvas.height = this.pageHeight * ratio
    ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.strokeStyle = 'red'
    ctx.fillStyle = "rgba(94,124,224,0.30)"
    // this.pointArray && this.pointArray.length > 0 && this.pointArray.map((item: any) => {
    //   ctx.strokeRect(item.x, item.y, item.width, item.height)
    //   ctx.fillRect(item.x, item.y, item.width, item.height)
    // })
    const scale = this.pageHeight / this.pdfSize[1] > this.pageWidth / this.pdfSize[0] ?
      this.pageWidth / this.pdfSize[0] : this.pageHeight / this.pdfSize[1]
    // const scale = this.scale;
    if (this.rectObj[page]) {
      ctx.fillStyle = "rgba(94,124,224,0.30)"
      this.rectObj[page].length > 0 && this.rectObj[page].map(rect => {
        ctx.fillRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
      })
    }
    // 绘制当前可编辑的高亮元素框
    console.log('this.currentIndex', page, this.editHightlight)
    if (this.editHightlight && this.editHightlight.length > 0) {
      this.editHightlight.map((item: any) => {
        // if(upItem && upItem.length> 0) {
        //   upItem.map(item => {
        if (item.locations && item.locations.length > 0) {
          // locations 是数组
          item.locations.map(itemLocation => {
            if (itemLocation.page == page) {
              itemLocation.location && itemLocation.location.length > 0 && itemLocation.location.map(rect => {
                ctx.strokeStyle = 'green'
                ctx.strokeRect(rect[0][0] * scale, rect[0][1] * scale, (rect[1][0] - rect[0][0]) * scale, (rect[2][1] - rect[0][1]) * scale);
              })
            }
          })
        }
      })
    }
    ctx.save()
  }
}
